<template>
  <div class="flex-container">
    <div class="left">
      <div style="margin-top: 15px; display: flex; justify-content: center">
        <el-button style="width: 86%;" class="el_button" size="small" @click="onimport"
          v-permission="{ action: 'org:edit' }">批量编辑</el-button>
      </div>
      <div class="list">
        <Tree ref="refTree" @toggleOrgId="toggleOrgId" styleName="middle2" ></Tree>
      </div>
    </div>
    <div class="right">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- <el-tab-pane label="单位信息" name="unitInfo" v-if="orgId!=''">
        <unitInfo ref="refunitInfo" :editOrgInfo="editOrgInfo" @getOrg="getOrg" :getLocationInfo="getLocationInfo"
          :getAddressflag="getAddressflag"></unitInfo>
        </el-tab-pane>
        <el-tab-pane label="成员信息" name="membership" v-if="orgId!=''">
          <membership ref="refmembership" :orgId="orgId" :role="role" @editState="editState" @getUnit="getUnit">
          </membership>
        </el-tab-pane> -->
        <el-tab-pane label="建筑物" name="buildings">
          <buildings ref="refbuildings" :orgInfo="orgInfo" @getFloor="getFloor" @getMounting="getMounting"></buildings>
        </el-tab-pane>
        <el-tab-pane label="楼层" name="floor">
          <floor ref="reffloor" :orgInfo="orgInfo" @getSpaces="getSpaces"></floor>
        </el-tab-pane>
        <el-tab-pane label="安装点" name="spaces">
          <spaces ref="refspaces" :orgInfo="orgInfo"></spaces>
        </el-tab-pane>
        <!-- <el-tab-pane label="平面图" name="ichnography" v-if="orgId != ''">
          <ichnography ref="refichnography" :orgId="orgId"></ichnography>
        </el-tab-pane> -->
      </el-tabs>
    </div>

    <!-- <div v-show="!orgId" class="no-warn-info">
      <img :src="wugj" class="img2" />
      <div>请在左侧选择单位</div>
    </div> -->
    
    <ImportBuildings ref="refImportBuildings"></ImportBuildings>
  </div>
</template>

<script>
import Unit from "./components/Unit";
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import { mapState } from "vuex";
import unitInfo from "./components/unitInfo";
import membership from "./membership/membership.vue"; //成员
import buildings from "./buildings/buildings.vue"; //建筑物
import floor from "./floor/floor.vue"; //楼层
import spaces from "./spaces/spaces.vue"; //安装点
import ichnography from "./ichnography/ichnography.vue"; //平面图
import { jsonp } from "vue-jsonp"; //使用jsonp
import Tree from "@components/tree/Unit.vue"; //组织机构
import { reqOrgList } from "@api/api.js";
import ImportBuildings from "./components/ImportBuildings.vue";

export default {
  name: "org",
  components: {
    Unit,
    Pagination,
    unitInfo,
    membership,
    buildings,
    floor,
    spaces,
    ichnography,
    Tree,
    ImportBuildings,
  },
  mixins: [tableStyleMixin],
  data() {
    return {
      wugj: require("@assets/images/datav/wugj.png"),
      dataList: [],
      isZoom: false,
      orgId: "",
      role: "",
      activeName: "unitInfo",
      editOrgInfo: {},
      getLocationInfo: {
        getLat: "",
        getLng: "",
        province: "",
        city: "",
        area: "",
        street: "",
        address: "",
      },
      getAddressflag: false, //地图选点
      orgFlag: false, //新增单位窗口是否弹出
      orgInfo:{},
    };
  },
  async mounted() {
    this.addListenAddress();
    // if (!this.spacesManage.organizationInfo.orgId && (this.user.roleName == 'ORG_ADMIN' || this.user.roleName == 'INSTERALL_USER')) {
    //   // 第一次登录进来需调用，因为有走执行先后顺序问题，导致第一次进来拿不到orgId  // 组织||装维
    //   this.getDataList()
    //   return
    // }
    // if (this.user.roleName == 'ORG_ADMIN' || this.user.roleName == 'INSTERALL_USER') {
    //   // 组织||装维
    //   this.orgId = this.spacesManage.organizationInfo.orgId;
    //   this.role = this.spacesManage.organizationInfo.role; //role==1为管理员
    //   this.activeName = "buildings";
    //   await this.$refs.refbuildings.clearinit(); //建筑物初始化
    //   await this.$refs.refbuildings.addListenAddress();
    //   await this.$refs.refbuildings.SpaceManager();
    // }
  },
  async created() { },
  watch: {},
  computed: {
    ...mapState(["user", "spacesManage"]),
  },
  methods: {
    onimport() {
      // this.$refs.refImportBuildings.OrgList();
      this.$refs.refImportBuildings.dialogVisible = true;
    },
    // 获取组织列表
    async getDataList() {
      let params = {
        tenantId: this.user.tenantId,
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgName: this.orgName,
        type: "1,2,3,4"
      };
      let res = await reqOrgList(params);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { rows } = res.data;
      let data = {
        orgId: rows[0].id,
        orgName: rows[0].orgName,
        role: rows[0].role,
      };
      this.orgId = data.orgId;
      this.role = data.role; //role==1为管理员
      this.activeName = "buildings";
      await this.$refs.refbuildings.clearinit(); //建筑物初始化
      await this.$refs.refbuildings.addListenAddress();
      await this.$refs.refbuildings.SpaceManager();
    },
    // 建筑物点击楼层数量
    getFloor(e) {
      this.activeName = "floor";
      this.$refs.reffloor.getFloor(e);
    },
    // 建筑物点击安装点数量
    getMounting(e) {
      this.activeName = "spaces";
      this.$nextTick(() => {
        this.$refs.refspaces.getMounting(e);
      });
    },
    // 楼层点击安装点数量
    getSpaces(e) {
      this.activeName = "spaces";
      this.$nextTick(() => {
        this.$refs.refspaces.getSpaces(e);
      });
    },
    getorgFlag(e) {
      this.orgFlag = e;
    },
    //更新单位列表
    getOrg(editForm) {
      // console.log(editForm);
      this.editOrgInfo = JSON.parse(JSON.stringify(editForm)); //编辑单位
      this.$refs.refUnit.getOrg();
    },
    async handleClick(tab, event) {
      // console.log(tab.paneName);
      // if (this.orgId == "") return;//没有单位时
      if (tab.paneName == "membership") {
        this.$refs.refmembership.getDataList();
      } else if (tab.paneName == "buildings") {
        this.$refs.refbuildings.addListenAddress();
        this.$refs.refbuildings.SpaceManager();
      } else if (tab.paneName == "floor") {
        this.$refs.reffloor.flag=true;
        await this.$refs.reffloor.SpaceManager();
      } else if (tab.paneName == "spaces") {
        this.$refs.refspaces.flag=true;
        this.$refs.refspaces.getreqParkList();
        this.$refs.refspaces.addListenAddress();
      } else if (tab.paneName == "ichnography") {
        this.$refs.refichnography.getBuildings();
      } else if (tab.paneName == "unitInfo") {
        this.$nextTick(() => {
          this.$refs.refunitInfo.RegionList();
          this.$refs.refunitInfo.cityArr();
          this.$refs.refunitInfo.areaArr();
          this.$refs.refunitInfo.RegionLevelList();
          this.$refs.refunitInfo.communitylList();
        });
      }
    },

    // 切换单位
    async toggleOrgId(data) {
      // console.log(data,'data111',this.orgInfo);
      // if (data.type != 4) return;
      if(this.orgInfo.orgId==data.orgId) return //点击相同的机构不走
      this.orgId = data.orgId;
      this.orgInfo=data;
      this.role = data.role || ""; //role==1为管理员
      // if (data.orgId == "") {
      //   // 全部单位
      //   this.activeName = 'buildings'
      //   await this.$refs.refbuildings.clearinit()//建筑物初始化
      //   await this.$refs.refbuildings.addListenAddress()
      //   await this.$refs.refbuildings.SpaceManager()
      //   // this.$refs.reffloor.clearinit()//楼层初始化
      //   // this.$refs.refspaces.clearinit()//安装点初始化
      //   // this.$refs.refichnography.clearinit()//平面图初始化
      //   return;
      // }
      this.activeName = "buildings";
      this.$nextTick(async () => {
        await this.$refs.refbuildings.clearinit(); //建筑物初始化
        await this.$refs.refbuildings.addListenAddress();
        await this.$refs.refbuildings.SpaceManager();
      })
    },
    // 移交权限
    // editState() {
    //   this.role = "2"; // 如果是普通管理员，把单位设置给其他成员
    //   this.$refs.refUnit.getOrg(); // 移交权限后更新列表
    //   // 单位列表管理员图标隐藏
    //   this.$refs.refUnit.flagtree = false;
    // },
    // 退出机构
    // getUnit() {
    //   this.$refs.refUnit.getDataList();
    // },
    // 监听获取经纬度
    addListenAddress() {
      window.addEventListener(
        "message",
        (event) => {
          // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
          let loc = event.data;
          if (loc && loc.module == "locationPicker" && !this.orgFlag) {
            //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
            this.getAddress(loc.latlng.lat, loc.latlng.lng, loc.poiname);
          }
        },
        false
      );
    },
    // 获取地址信息
    getAddress(lat, lng, poiname) {
      jsonp(
        `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53`,
        {
          output: "jsonp",
        }
      )
        .then((res) => {
          this.getAddressflag = !this.getAddressflag;
          // console.log(res);
          let { province, city, district } = res.result.ad_info;
          let { title } = res.result.address_reference.town;
          this.$set(this.getLocationInfo, "getLat", lat);
          this.$set(this.getLocationInfo, "getLng", lng);
          this.$set(this.getLocationInfo, "province", province);
          this.$set(this.getLocationInfo, "city", city);
          this.$set(this.getLocationInfo, "area", district);
          this.$set(this.getLocationInfo, "street", title);
          this.$set(
            this.getLocationInfo,
            "address",
            this.stripscript(poiname).length > 20
              ? this.stripscript(poiname).substr(0, 20)
              : this.stripscript(poiname)
          );
        })
        .catch((err) => {
          // console.log(err, "err");
        });
    },
    // 过滤特殊字符
    stripscript(s) {
      let pattern = new RegExp(
        "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—|{}【】‘；：”“'。，、？]"
      );
      let rs = "";
      for (let i = 0; i < s.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, "");
      }
      return rs;
    },
    //   点击缩放左侧
    zoomClick() {
      this.isZoom = !this.isZoom;
    },
  },
};
</script>

<style scoped lang="less">
@import url("~@views/orgManage/orgList.less");
@import url("~@views/style/tablePage.less");

// 导航栏颜色
::v-deep .el-tabs__item {
  color: @primaryThemeTxtColor2;
  width: 96px;
  text-align: center;
  padding: 0 !important;
}

::v-deep .el-tabs__active-bar {
  background-color: #7367f0;
}

::v-deep .el-tabs__item.is-active {
  color: #7367f0;
}

::v-deep .el-dialog__body {
  padding: 0px 20px;
}

// 导航栏线条颜色
::v-deep .el-tabs__nav-wrap::after {
  // background: @primaryBgcolor11;
  background: #ccc;
}

::v-deep .el-tabs__nav {
  padding: 5px 20px;
}

::v-deep .el-tabs__active-bar {
  // padding: 0px 20px;
  position: absolute;
  bottom: 0;
  left: 20px;
  height: 2px;
  z-index: 1;
}

::v-deep .el-tabs__header {
  margin: 0;
}

.no-warn-info {
  width: 81%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  align-content: center;
  margin-top: 1.5%;
  color: @primaryThemeTxtColor;
  font-size: 15px;

  >img {
    width: 150px;
    height: 150px;
    margin-bottom: 10px;
  }

  .img2 {
    width: 170px;
    height: 170px;
  }
}
</style>
